<template>
  <el-card class="task-stats-card">
    <div slot="header">任务统计</div>
    <div class="stats-item">
      <span class="stats-label">本月任务</span>
      <span class="stats-value">{{ monthTaskCount }}</span>
    </div>
    <div class="stats-item">
      <span class="stats-label">已完成</span>
      <span class="stats-value">{{ completedCount }}</span>
    </div>
    <div class="stats-charts">
      <div class="chart-item">
        <span>本月任务</span>
        <el-progress

          :percentage="monthProgress"
          :stroke-width="12"
          style="margin-top: 10px;"
        ></el-progress>
      </div>
      <div class="chart-item">
        <span>已完成</span>
        <el-progress
          :percentage="completedProgress"
          :stroke-width="14"
          color="#13ce66"
          style="margin-top: 10px;"
        ></el-progress>
      </div>
    </div>
  </el-card>
</template>

<script>
import { getTaskAllCount } from '@/api/task'

export default {
  name: 'TaskStats',
  data () {
    return {
      monthTaskCount: 0,
      completedCount: 0,
      totalTasksLastMonth: 0
    }
  },
  created () {
    this.getCount()
  },
  computed: {
    monthProgress () {
      const {
        monthTaskCount,
        totalTasksLastMonth
      } = this
      if (typeof monthTaskCount !== 'number' || typeof totalTasksLastMonth !== 'number' || totalTasksLastMonth <= 0) {
        return 0
      }
      let percentage = (monthTaskCount / totalTasksLastMonth) * 100
      return Math.min(100, Math.max(0, percentage))
    },
    completedProgress () {
      const {
        monthTaskCount,
        completedCount
      } = this
      if (monthTaskCount <= 0) return 0
      let percentage = (completedCount / monthTaskCount) * 100
      return Math.min(100, Math.max(0, percentage))
    }
  },
  methods: {
    getCount () {
      getTaskAllCount()
        .then(res => {
          if (res && res.data) {
            this.monthTaskCount = res.data.totalTasksCurrentMonth || 0
            this.completedCount = res.data.completedTasksCurrentMonth || 0
            this.totalTasksLastMonth = res.data.totalTasksLastMonth || 0
          } else {
            console.warn('接口返回数据结构异常：', res)
            // 可以在这里设置默认值或提示用户
          }
        })
        .catch(err => {
          console.error('获取任务统计数据失败:', err)
          // 可以弹出提示或使用默认值
        })
    }
  }
}
</script>

<style scoped>
.task-stats-card {
  height: fit-content;
}

.stats-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.stats-label {
  color: #666;
}

.stats-value {
  font-weight: bold;
}

.stats-charts {
  margin-top: 20px;
}

.chart-item {
  margin-bottom: 10px;
}
</style>
